<template>
  <div class="role">
    <PageSearch
      :searchFormConfig="searchFormConfig"
      @handleResetClick="handleResetClick"
      @handleQueryClick="handleQueryClick"
    />
    <PageTable
      :pageContentConfig="pageContentConfig"
      pageName="role"
      ref="pageContentRef"
      @newBtnClick="handleNewData"
      @editBtnClick="handleEditData"
    />
    <PageModel
      :modelConfig="modelConfig"
      pageName="role"
      ref="pageModelRef"
      :otherInfo="otherInfo"
      :defaultInfo="defaultInfo"
    >
      <div class="menu-tree">
        <el-tree
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckchange"
          ref="treeRef"
        >
        </el-tree>
      </div>
    </PageModel>
  </div>
</template>

<script lang="ts">
import PageSearch from '@/components/PageSearch'
import PageTable from '@/components/PageTable'
import PageModel from '@/components/PageModel'
import { computed, defineComponent, ref, nextTick } from 'vue'

import { UsePageModel } from 'hooks/UsePageModel'
import { UsePageSearch } from 'hooks/UsePageSearch'

import { searchFormConfig } from './config/searchFormConfig'
import pageContentConfig from './config/pageContentConfig'
import modelConfig from './config/modalConfig'
import { menuMapLeafKeys } from 'utils/mapMenus'
import { useStore } from '@/store'
import { ElTree } from 'element-plus'
export default defineComponent({
  components: { PageTable, PageSearch, PageModel },
  name: 'role',
  setup() {
    const [pageContentRef, handleResetClick, handleQueryClick] = UsePageSearch()
    // 处理pageModel的hook
    const editCallback = (item: any) => {
      const leafKeys = menuMapLeafKeys(item.menuList)

      nextTick(() => {
        treeRef.value?.setCheckedKeys(leafKeys, false)
      })
    }

    const treeRef = ref<InstanceType<typeof ElTree>>()

    const [handleNewData, handleEditData, pageModelRef, defaultInfo] =
      UsePageModel(undefined, editCallback)
    const store = useStore()
    const menus = computed(() => store.state.entireMenu)

    const otherInfo = ref({})

    const handleCheckchange = (data1: any, data2: any) => {
      const menuList = [...data2.checkedKeys, ...data2.halfCheckedKeys]
      otherInfo.value = { menuList }
    }
    return {
      pageContentConfig,
      searchFormConfig,
      modelConfig,
      pageContentRef,
      handleResetClick,
      handleQueryClick,
      handleNewData,
      handleEditData,
      pageModelRef,
      defaultInfo,
      menus,
      otherInfo,
      handleCheckchange,
      treeRef
    }
  }
})
</script>

<style scoped lang="scss">
.menu-tree {
  margin-left: 40px;
}
</style>
